const dgram = require("dgram");
const server = dgram.createSocket("udp4");
const witness_config = require("./witness_client_conf.json");
var Web3 = require("web3");
var port = witness_config["witness_port"];
server.on("error", (err) => {
  console.log("server error:" + err.stack);
  server.close();
});
server.on("listening", () => {
  const addr = server.address();
  console.log(`run ${addr.address}:${addr.port}`);
});
server.on("message", (msg, rinfo) => {
  var msg2obj = JSON.parse(msg);
  console.log(
    "收到来自%s的投票信息，待监控的合约地址为%s",
    rinfo.address,
    msg2obj.con_address
  );
  var web3 = new Web3(witness_config["rpc_node"]);
  var witness_contract = new web3.eth.Contract(
    JSON.parse(msg2obj.abi),
    msg2obj.con_address
  );
  witness_contract.events
    .vote_event(
      {
        filter: {},
        fromBlock: 11541,
      },
      function (error, event) {
        console.log(error);
      }
    )
    .on("data", function (event) {
      // Fires on each incoming event with the event object as argument
      var status = event.returnValues.status;
      var result;
      switch (status) {
        case "error_3":
          result = "投票超时，当前合约已关闭";
          break;
        case "error_4":
          result = "该账户未经授权";
          break;
        case "error_5":
          result = "不可以重复投票";
          break;
        case "error_6":
          result = "投票域名与合约域名不一致";
          break;
        default:
          result = "投票成功";
      }
      console.log(
        event.returnValues.voter +
          "\t===>\t" +
          event.returnValues.content +
          "\t" +
          result
      );
    })
    .on("changed", function (event) {
      // Fires on each event which was removed from the blockchain.
      console.log(event);
    })
    .on("error", function (error, receipt) {
      // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
      console.log(error);
    });
});
server.bind(port);
